<template>
  <div>
    <div class="node" v-has="{action: 'wx:refund:list', effect: 'move'}">
      <div class="search_box topSelect">
        
        <div class="searchBox1" style="margin-left: 20px">
          <el-button size="small" plain icon="el-icon-search" @click="getQueryData">查询</el-button>     
        </div>
      </div>
      <Panel title="退款申请列表" :intro='intro'>
        <div slot='ext' class="examine" >
          <!-- <div class="adopt" @click="()=>editStore()">新增</div> -->
      </div>
      <TableEncapsulation
        slot="body"
        :tableConfig="tableConfig"
        :tableData="tableData"
      >
      <template slot="operation" slot-scope="operation">
            <el-button size="mini" icon="el-icon-circle-check"
              v-has="{action: 'wx:refund:refund', effect: 'move'}"
              v-if="operation.row.state == 0"
              @click="()=>band(operation.row, 1)"
            >同意退款</el-button>
            <!-- <el-button size="mini" icon="el-icon-circle-close"
              v-has="{action: 'wx:refund:refuse', effect: 'move'}"
              v-if="operation.row.state == 0"
              @click="()=>refulse(operation.row)"
            >拒绝退款</el-button>
           
            <el-button size="mini" icon="el-icon-document"
              v-has="{action: 'charge:wx:refund:list', effect: 'move'}"
              v-if="operation.row.state != 0"
              @click="()=>record(operation.row.oid)"
            >退款记录</el-button> -->
          </template>
          <TablePager
            slot="pager"
            v-if="pager.use"
            :size="pager.size"
            :pageChange="pageChange"
            :show-total="pager.showTotal"
            :total="pager.total"
            :current="pager.current"
          >
            <span class="demonstration">GO></span>
          </TablePager>
      </TableEncapsulation>
      </Panel>

      <ModalPanel 
        :visible='visible'
        title="拒绝退款"
        :onCancel="onCancel"
        class="bannerDialog"
        :onOk="onSubmit">
        <div>
          <ModifyForm
            :hiddenBtn='true'
            :editColumn='editColumn'
            :updateData="updateData"
            labelWidth='100px'
            ref="configModal"
            class="ModifyForm"
            :temporaryData='modalDataR'>
          </ModifyForm>
        </div>
      </ModalPanel>

      <ModalPanel 
        :visible='visible1'
        :title="totalPrice"
        :onCancel="onCancel1"
        :onOk="onSubmit1"
        :showFooter="false">
        <div>
          <div slot="body">
            <TableEncapsulation
              :tableConfig="tableConfig1"
              :tableData="tableData1"
            >
              <template slot="operation" slot-scope="operation">
               <el-input v-model="refundList[operation.index]"   @change="(val) => fet(val,operation.index, operation.row.canRefund)" :placeholder="operation.row.canRefund"  type="number" ></el-input>
               <div style="color: red;display: none" :ref="'ref'+operation.index">输入值必须为0-{{operation.row.canRefund}}</div>
              </template>
              <TablePager
                slot="pager"
                layout='prev, pager, next, total'
                v-if="pager1.use"
                :size="pager1.size"
                :pageChange="pageChange1"
                :show-total="pager1.showTotal"
                :total="pager1.total"
                :current="pager1.current"
              >
              <span class="demonstration">GO></span>
            </TablePager>
          </TableEncapsulation>
          <el-button style="margin-top: 20px;margin-left: 80%;" type="danger" @click="confirmRefund">确认退款</el-button>
          </div>
          
        </div>
      </ModalPanel>
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'wx:refund:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import { objectFilter } from "@/tools/array";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
import { dateFormat } from "@/tools/time";

export default {
  name: "refund",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput,
    ModifyForm,
    ModalPanel
  },
  data() {
    return {
      intro: {
        title: '退小程序退款-介绍说明',
        content: `<ul><li>微信小程序用户申请退款列表</li></ul><p><br></p><ul><li>注意：</li></ul><ol><li class="ql-indent-1">同意退款时，若单笔充值金额不足，需要分多笔退回，退款金额不能超过充值金额；按微信退款规则，充值超过一年的订单不能退款</li><li class="ql-indent-1">主动向用户发起退款请在‘小程序用户’-&gt;‘微信用户管理’-&gt;‘充值订单’ 中操作退款</li></ol><p><br></p>`
      },
      visible:false,
      refundPrice: true,
      priceNowEque: true, //提示输入总金额是否等于申请退款金额
      refundPriceNow: 0,
      totalPrice:'0',
      modalDataR:{},
      tableData: [],
      visible1: false,
      tableData1: [],
      editId:'',
      orderId: '',
      refundType: '',
      searchs:{
        component: 'refund',
        page: 1,
        state:'',
        phone: '',
        plate: '',
        appointmentTime:[],
      },
      pager: {
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      pager1: {
        use: true,
        total: 0,
        current: 1,
        size: 20,
        showTotal: true
      },
      name: '',
      operation: true,
      refundList:[],
      modalData:{},
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
       editColumn: [
        {
          name: "拒绝原因",
          prop: "reason",
          type: "text",
          required: false,
          width: 24
        },
        {
          name: "备注",
          prop: "mark",
          type: "text",
          required: false,
          width: 24
        },
      ],
    };
  },
  created() {
    let now = new Date().getTime() + 3600 * 1000 * 24
    let year = new Date(now).getFullYear()
    let month = new Date(now).getMonth() 
    let day = new Date(now).getDate()
    let last = new Date().getTime() - 3600 * 1000 * 24 * 6
    let lastYear =  new Date(last).getFullYear() 
    let LastMonth = new Date(last).getMonth() 
    let lastDay = new Date(last).getDate()
    this.searchs.appointmentTime = [ new Date(lastYear, LastMonth, lastDay, 0, 0,0), new Date(year, month, day, 0, 0,0)]
    this.getQueryData();
  },
  computed: {
    tableConfig () {
      return {
        selection: true,
        columnConfig: [
       
          {
            label: "退款单号",
            type: "text",
            prop: "oid",
            align: "center"
          },
          {
            label: "申请退款金额",
            type: "text",
            prop: "price",
            align: "center",
            class: 'bolder'
          },
          {
            label: "用户",
            type: "text",
            prop: "nick",
            align: "center"
          },
          {
            label: "手机号",
            type: "text",
            prop: "phone",
            align: "center"
          },
          {
            label: "申请时间",
            type: "text",
            prop: "createTime",
            align: "center"
          },
           {
            label: "实际退款金额",
            type: "text",
            prop: "refundPrice",
            align: "center"
          },
          {
            label: "退款状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val => val == 1 ? '已同意': val ==2 ? '已拒绝': val ==3 ? '用户取消': '待处理',
            class: val => val == 1 ? 'agree': val ==2 ? 'refuse': val ==3 ? 'cancel': 'wait',
          },
          {
            label: "车牌号",
            type: "text",
            prop: "plate",
            align: "center"
          },
          {
            label: "操作时间",
            type: "text",
            prop: "processTime",
            align: "center"
          },
          {
            label: "操作人",
            type: "text",
            prop: "operator",
            align: "center"
          },
          {
            label: "消息",
            type: "text",
            prop: "msg",
            align: "center"
          },
          {
            label: "备注",
            type: "text",
            prop: "mark",
            align: "center"
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:280
          }
        ].filter(Boolean)
        }
    },
    tableConfig1 () {
      return {
        selection: true,
        columnConfig: [
          // {
          //   label: "id",
          //   type: "text",
          //   prop: "id",
          //   align: "center"
          // },
          // {
          //   label: "用户",
          //   type: "text",
          //   prop: "uName",
          //   align: "center"
          // },
          {
            label: "充值金额",
            type: "text",
            prop: "price",
            align: "center"
          },
          {
            label: "已退款金额",
            type: "text",
            prop: "refunded",
            align: "center"
          },
          {
            label: "订单号",
            type: "text",
            prop: "oid",
            align: "center"
          },
          // {
          //   label: "退款金额",
          //   type: "slot",
          //   prop: "pri",
          //   slotName: "operation",
          //   align: "center"
          // },
         
          {
            label: "支付时间",
            type: "text",
            prop: "payTime",
            align: "center"
          },
          {
            label: "状态",
            type: "other",
            prop: "state",
            fnc: val => val == 1 ? '半年内': val ==2 ? '超过半年':'超过一年',
            class: val => val == 1 ? 'agree': val ==2 ? 'wait': 'refuse',
            align: "center"
          },
          {
            label: "可退款金额",
            type: "text",
            prop: "canRefund",
            align: "center"
          },
          this.refundPrice && {
            type: "operation",
            align: "center",
            label: "退款金额",
            width:180
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    async getQueryData() {
      let current =  this.pager.current
      let size =  this.pager.size
      let search = objectFilter({ current, size})
      const res = await request({
        url: "/manage/refund/order/query",
        method: "POST",
        data: search
      });
      this.tableData = res.data.records
      this.pager.total = res.data.total
      this.pager.current = res.data.current
    },
    pageChange(val) {
      this.pager.current = val;
      this.getQueryData();
    },
    pageChange1(val) {
      this.pager1.current = val;
      this.getQuery();
    },
    changeSearch(key, val) {
      this.searchs[key] = val;
      this.pager.current = 1;
    },
    charge(rowData){
      let data = {
        price:0,api:rowData.id,detail:''
      }
      this.modalData = data
      this.visible = true
      
    },
    exemption(id){
       this.modalData = {id}
       this.visible = true
    },
    band(row, type){
      this.editId = row.uid
      this.orderId = row.oid
      this.refundPriceNow = row.price
      this.totalPrice = "可退款充值订单(￥"+row.price+")"
      this.refundType = type
      this.getQuery() 
    },
    refulse(row){
      this.modalDataR = row
      this.visible = true
    },
    async updateData(values){
      const { oid, reason, mark } = values
      let res = await request({
          url: '/wx/refund/refuse',
          method: 'POST',
          data: { oid, reason, mark }
      })
      if (res.code !==0) return
      this.$message.success('编辑成功')
      this.visible = false
      this.getQueryData()
    },
    //query
    // 输入格式：yyyy-MM-DD或yyyy-MM
    daysBetween(sDate1, sDate2) {
    //Date.parse() 解析一个日期时间字符串，并返回1970/1/1 午夜距离该日期时间的毫秒数
    var time1 = Date.parse(new Date(sDate1));
    
    var time2 = Date.parse(new Date());
    var nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24));
    return nDays;
},

    async getQuery(){
      let page =  this.pager1.current
      let size =  this.pager1.size
      let res = await request({
      url: "/charge/wx/available/refund",
      method: "POST",
      data: {uid:this.editId,page, size}
      });
      if(res.page.list){
        res.page.list.map(item => {
          var day = this.daysBetween('20'+item.payTime,'20'+item.payTime)
          if(day>365){
            item.state = 3
          }else if(day >179){
            item.state = 2
          }else{
            item.state = 1
          }
          return item
        })
      }
      let data = res.page.list
      var refundPriceNow = this.refundPriceNow
      let refundList = this.refundList
      var apply = refundPriceNow
      data.map((item,index) => {
        item.canRefund = item.refundable
        if(apply==0){
          refundList[index] = 0
        }
        else if(apply<= item.canRefund){
          refundList[index] = apply
          apply =0
        }else{
          refundList[index] = item.canRefund
          apply = (parseFloat(apply) - parseFloat(item.canRefund)).toFixed(2)
        }
        return item
      })
      this.tableData1 = data
      
      this.visible1 = true
      this.pager1.total = res.page.totalCount
      this.pager1.current = res.page.currPage
      let this_ = this
      setTimeout(() => {
        this_.fetNone(data)
      }, 200);
    },
    fetNone(data){
      let that = this
      data.map((item, index) => {
        var name = 'ref'+index
        if(that.$refs[name].style.display =='block'){
          console.log(name)
          this.$refs[name].style.display = 'none' 
        }
        
      })
    },
    fet(val,index, max){
      let name = 'ref'+index
      if(val >=0 && val<= max){
        this.$refs[name].style.display = 'none' 
      }else{
        this.$refs[name].style.display = 'block' 
      }
      
    },
    formdialog() {
      let arr = this.tableData1
        .filter(item => item.canRefund)
        .map(item => ({
          [item.prop]: {
            required: true,
            message: item.name + "不能为空",
            trigger: "blur"
          }
        }));
      return arrayToObject(arr, "prop");
    },
    
    async bindId(parkId) {
    //  const {parkId , name, contacts, contactsPhone, siteId , company , address, id } = values
     let url = "/parking/update"
     let msg = "编辑成功" 
     let res = await request({
       url: url,
       method: "POST",
       data:{parkId ,id: this.editId }
     })
     if(res.code !==0) return
      this.$message.success(msg)
      this.visible1 = false
      // this.$router.go(-1)
    },
    onCancel(){
      this.visible = false
    },
    onCancel1(){
      this.visible1 = false
      this.refundList = []
    },
    async onSubmit1(){
      // this.$refs['configModal'].onSubmit()
    },
    async confirmRefund(){
      let url, msg
      url = this.refundType ==1 ? '/wx/refund/refund' : '/wx/refund/manual/refund'
      msg = '成功'
      if(this.refundList.length <= 0){
        this.$message.error('至少输入一条订单退款金额') 
        return false
      }
      let tag = {}, subData = [], priceNum = 0
      let tableData = this.tableData1
      this.refundList.map((item, index) => {
        if(item >0 && item){
          tag ={price: item, oid: tableData[index].oid}
          subData.push(tag)
          priceNum+=parseFloat(item)
        }
      })
      var confirmMsg = ''
      priceNum = (priceNum).toFixed(2)
      console.log('----',typeof priceNum, typeof this.refundPriceNow)
      console.log('----', priceNum,  this.refundPriceNow)
      if(priceNum != this.refundPriceNow ){
        confirmMsg = '合计输入金额不等于申请退款金额；'
        this.$confirm(confirmMsg, '操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async () => {
        let res = await request({
          url: url,
          method: 'POST',
          data: { list: subData, oid: this.orderId }
        })
        this.refundList = []
        if (res.code !==0) return
        this.$message.success(res.msg)
        this.visible1 = false
        this.getQueryData()
        })
      }else{
        let res = await request({
          url: url,
          method: 'POST',
          data: { list: subData, oid: this.orderId }
        })
        this.refundList = []
        if (res.code !==0) return
        this.$message.success(res.msg)
        this.visible1 = false
        this.getQueryData()
      }
    },
    async onSubmit(){
      this.$refs['configModal'].onSubmit()
    },
    record(id){
      this.$router.push({ path: "/refund/record",query:{roid:id} })
    },
    remove(id){
       this.$confirm('确认删除吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        let res = await request({
          url: '/parking/delete',
          method: 'POST',
          dataType: 'json',
          data:[id]
        })
        if(res.code !==0) return
        this.$message.success('删除成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.getQueryData()
      })
    },
  }
}
</script>
<style lang='scss' module>
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}


</style>